package com.caijin.web.controller.system.user;

import com.caijin.common.constant.UserConstants;
import com.caijin.common.core.domain.Result;
import com.caijin.common.util.EntityUtil;
import com.caijin.common.core.domain.vo.UserVO;
import com.caijin.system.service.IStudentService;
import com.caijin.system.service.ITeacherService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户 业务处理
 *
 * @author Peas
 * @since 2021-01-12
 */
@RestController
@RequestMapping("/system/")
@CrossOrigin
public class UserController {

    @Autowired
    private IStudentService studentService;

    @Autowired
    private ITeacherService teacherService;

    /**
     * 用户注册
     */
    @ApiOperation(value = "用户注册")
    @RequestMapping(path = "/register", method = RequestMethod.POST)
    public Result register(@RequestBody UserVO registerInfo) {
        return StringUtils.equals(UserConstants.TEACHER_TYPE, registerInfo.getType()) ? teacherService.register(EntityUtil.toTeacher(registerInfo)) : studentService.register(EntityUtil.toStudent(registerInfo));
    }

    /**
     * 用户登录
     */
    @ApiOperation(value = "用户登录")
    @RequestMapping(path = "/login", method = RequestMethod.POST)
    public Result login(@RequestParam("id") Long id,
                        @RequestParam("password") String password,
                        @RequestParam("type") String type,
                        HttpServletRequest request) {
        return StringUtils.equals(UserConstants.STUDENT_TYPE, type) ? studentService.login(request, id, password) : teacherService.login(request, id, password);
    }

    /**
     * 修改用户信息
     */
    @ApiOperation(value = "修改用户信息")
    @RequestMapping(path = "/modified", method = RequestMethod.POST)
    public Result modified(@RequestParam("userType") String userType,
                           @RequestParam("userId") Long userId,
                           @RequestParam("avatar") String avatar) {
        return StringUtils.equals(UserConstants.TEACHER_TYPE, userType) ? teacherService.modifiedUserInfo(userId, avatar) : studentService.modifiedUserInfo(userId, avatar);
    }

    /**
     * 获取用户信息
     */
    @ApiOperation(value = "获取用户信息")
    @RequestMapping(path = "/getUser", method = RequestMethod.GET)
    public Result getUser(@RequestParam("userType") String type,
                          @RequestParam("userId") Long id) {
        return Result.ok().data("user", StringUtils.equals(UserConstants.TEACHER_TYPE, type) ? EntityUtil.teacherToUserDTO(teacherService.getById(id)) : EntityUtil.studentToUserDTO(studentService.getById(id)));
    }

}
